Page({
  data: {
    // 考试基本信息
    score: 0,
    grade: "",
    assessment: "",
    examName: "",
    examTime: "",
    timeSpent: "",
    maxScore: 0,
    scorePercentage: 0, // 新增：分数百分比，用于圆环绘制
    
    // 统计数据
    totalQuestions: 0,
    correctAnswers: 0,
    wrongAnswers: 0,
    unansweredCount: 0,
    accuracy: 0,
    
    // 题型分析
    questionTypes: [],
    
    // 错题列表
    wrongQuestionsList: [],
    
    // 原始题目数据（用于显示题型）
    questions: []
  },
  
  onLoad() {
    try {
      // 从本地存储获取考试结果
      const examResult = wx.getStorageSync('latestExamResult');
      // 获取原始题目数据
      const questions = wx.getStorageSync('examQuestions') || [];
      
      if (!examResult) {
        throw new Error('未找到考试结果数据');
      }
      
      // 设置页面数据
      this.setData({
        // 基本信息
        score: examResult.score,
        maxScore: examResult.maxScore,
        scorePercentage: examResult.scorePercentage, // 保存分数百分比
        grade: examResult.grade,
        assessment: examResult.assessment,
        examName: examResult.examName,
        examTime: examResult.examTime,
        timeSpent: examResult.timeSpent,
        
        // 统计数据
        totalQuestions: examResult.totalQuestions,
        correctAnswers: examResult.correctAnswers,
        wrongAnswers: examResult.wrongAnswers,
        unansweredCount: examResult.unansweredCount,
        accuracy: examResult.accuracy,
        
        // 题型分析
        questionTypes: examResult.questionTypes,
        
        // 错题列表
        wrongQuestionsList: examResult.wrongQuestionsList,
        
        // 原始题目数据
        questions: questions
      });
      
      // 确保画布渲染完成后再绘制圆环
      setTimeout(() => {
        this.drawScoreCircle(examResult.scorePercentage || examResult.score / examResult.maxScore * 100);
      }, 50);
      
    } catch (error) {
      console.error('加载考试报告失败:', error);
      wx.showToast({
        title: '加载报告失败',
        icon: 'none',
        duration: 2000
      });
      
      // 2秒后返回上一页
      setTimeout(() => {
        wx.navigateBack({
          delta: 1
        });
      }, 2000);
    }
  },
  
  // 绘制分数圆环
  drawScoreCircle(scorePercentage) {
    return new Promise((resolve, reject) => {
      try {
        const query = wx.createSelectorQuery().in(this);
        
        // 方法1：使用canvas-id选择器（推荐）
        query.select('#scoreCircle')
          .fields({ node: true, size: true })
          .exec((res) => {
            if (!res || !res[0] || !res[0].node) {
              reject(new Error('Canvas元素未找到'));
              return;
            }
  
            const canvas = res[0].node;
            const ctx = canvas.getContext('2d');
            const width = res[0].width;
            const height = res[0].height;
            
            // 适配高清屏
            const dpr = wx.getSystemInfoSync().pixelRatio;
            canvas.width = width * dpr;
            canvas.height = height * dpr;
            ctx.scale(dpr, dpr);
  
            // 绘制逻辑
            const radius = Math.min(width, height) * 0.4;
            const centerX = width / 2;
            const centerY = height / 2;
            const lineWidth = 10;
  
            // 背景圆环
            ctx.beginPath();
            ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
            ctx.lineWidth = lineWidth;
            ctx.strokeStyle = '#f0f0f0';
            ctx.stroke();
  
            // 进度圆环
            const angle = (scorePercentage / 100) * Math.PI * 2;
            ctx.beginPath();
            ctx.arc(centerX, centerY, radius, -Math.PI/2, angle - Math.PI/2);
            ctx.lineWidth = lineWidth;
            ctx.strokeStyle = this.getProgressColor(scorePercentage);
            ctx.lineCap = 'round';
            ctx.stroke();
  
            resolve();
          });
      } catch (error) {
        reject(error);
      }
    });
  },

  getProgressColor(percentage) {
    if (percentage >= 80) return '#52c41a'; // 绿色
    if (percentage >= 60) return '#faad14'; // 黄色
    return '#ff4d4f'; // 红色
  },
  
  // 重新练习按钮点击事件
  reviewAll() {
    wx.showModal({
      title: '重新练习',
      content: '确定要重新开始考试吗？当前成绩将被清空。',
      success: (res) => {
        if (res.confirm) {
          // 清除之前的考试数据
          wx.removeStorageSync('latestExamResult');
          
          // 返回考试页面重新开始
          wx.navigateTo({
            url: '/pages/exam/exam',
            fail: () => {
              // 如果navigateTo失败，尝试redirectTo
              wx.redirectTo({
                url: '/pages/exam/exam'
              });
            }
          });
        }
      }
    });
  },
  
  // 查看错题按钮点击事件（新增）
  viewWrongQuestions() {
    if (this.data.wrongQuestionsList.length === 0) {
      wx.showToast({
        title: '没有错题',
        icon: 'none'
      });
      return;
    }
    
    // 可以跳转到专门的错题页面
    wx.navigateTo({
      url: '/pages/wrongQuestions/wrongQuestions'
    });
  }
});
    